import Vue from "vue";
import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [
    {
        path: "/",
        redirect: "/login"
    },
    {
        path: "/login",
        component: () =>
            import(/* webpackChunkName: "user" */ "../views/Login.vue")
    },
    {
        path: "/register",
        component: () =>
            import(/* webpackChunkName: "user" */ "../views/Register.vue")
    },
    {
        path: "/password",
        component: () =>
            import(/* webpackChunkName: "user" */ "../views/Password.vue")
    },
    {
        path: "/edit",
        component: () =>
            import(/* webpackChunkName: "user" */ "../views/Edit.vue")
    },
    {
        path: "/admin",
        component: () => import("@/views/admin/Index.vue"),
        children: [
            {
                path: "home",
                component: () => import("@/views/admin/Home.vue")
            },
            {
                path: "my",
                component: () => import("@/views/admin/My.vue")
            }
        ]
    }
];

const router = new VueRouter({
    mode: "history",
    base: process.env.BASE_URL,
    routes
});

router.beforeEach((to, from, next) => {
    if (
        ["/login", "/register"].includes(to.path) ||
        window.sessionStorage.getItem("token")
    ) {
        next();
    } else {
        next("/login");
    }
});

export default router;
